package com.huobao.yunying.activitys.muyingquan;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simple.eventbus.EventBus;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ViewInject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.BitmapTools;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.PopupFabu;
import com.huobao.yunying.utils.PopupWuliu;
import com.huobao.yunying.utils.ThreadPoolUtils;
import com.huobao.yunying.utils.UserUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.Log2File;
import com.xrz.sxm.base.utils.ToolLoading;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.tv.TvInputService.HardwareSession;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import io.vov.vitamio.utils.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import net.bither.util.NativeUtil;

public class Act_Quanzi_Fatie extends HuobaoBaseActivity implements OnClickListener {
	@ViewInject(R.id.fatie_camera)
	private ImageView Img_Camera;
	private List<String> pics;// 添加的图片集合
	@ViewInject(R.id.AddPicLinearLayout)
	private LinearLayout addPicLayout;// 添加的图片的LinearLayout
	private String mSelectPhoto;
	private View itemView;
	@ViewInject(R.id.quanziedit_biaoti)
	private EditText mEdit_BiaoTi;
	@ViewInject(R.id.quanziedit_content)
	private EditText mEdit_Content;
	private String Str_Biaoti, Str_content;
	private int type = 7;
	private int user_id;
	@ViewInject(R.id.tv_pop)
	private TextView Tv_Pop;
	private String id = "";
	private List<FaTieQuanZi> datas = new ArrayList<FaTieQuanZi>();

	@Override
	protected int getContentView() {
		return R.layout.layout_quanzifatie;
	}

	@Override
	protected String getTitleText() {
		return null;
	}

	@Override
	protected void init() {
		View RightView = LayoutInflater.from(this).inflate(R.layout.item_button, null);
		TextView Btn_Click = (TextView) RightView.findViewById(R.id.btn_click);
		mAbTitleBar.setVisibility(View.VISIBLE);
		mAbTitleBar.addRightView(RightView);
		changeQuanziTitle();
		pics = new ArrayList<String>();
		Img_Camera.setOnClickListener(this);
		user_id = UserUtils.getUserid(Act_Quanzi_Fatie.this);
		id = getIntent().getStringExtra("id");
		Btn_Click.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Str_Biaoti = mEdit_BiaoTi.getText().toString();
				Str_content = mEdit_Content.getText().toString();
				if (TextUtils.isEmpty(Str_Biaoti) || TextUtils.isEmpty(Str_content)) {
					Toast.makeText(Act_Quanzi_Fatie.this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
					return;
				}
				if(TextUtils.isEmpty(id)){
					Toast.makeText(Act_Quanzi_Fatie.this, "请选择圈子", 1).show();
					return;
				}
					
				// 上传图片
				UpLoadPic();
			}
		});

		Tv_Pop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 获取能发布帖子的圈子
				Map<String, String> map = HttpUtil.getParams("app", "postbar", "act", "grouparr");
				Http.getInstant().sendRequest(context, false, map, new HttpListener() {
					@Override
					public void onHttpSuccess(String result) {
						JSONObject jsonObject = JSON.parseObject(result);
						datas = jsonObject.parseArray(jsonObject.getString("retval"), FaTieQuanZi.class);
						// 显示popwindow
						PopupFabu.showPop(Act_Quanzi_Fatie.this, datas, Tv_Pop, new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
								PopupFabu.dismiss();
								id = datas.get(position).getGid();
								Tv_Pop.setText(datas.get(position).getGname());
							}
						});
					}

					@Override
					public void onHttpError(String error) {

					}
				});
			}
		});
	}

	private void sendMsg(String str) {
		Message message = Message.obtain();
		message.what = 2;
		message.obj = str;
		handler.sendMessage(message);
	}

	// 运用线程池上传图片
	private void UpLoadPic() {
		ToolLoading.ShowLoading(context);
		ThreadPoolUtils.newInstant().submit(new Runnable() {
			@Override
			public void run() {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < addPicLayout.getChildCount(); i++) {
					String path = (String) addPicLayout.getChildAt(i).getTag();
					String picpath = uploadImgsyc(path);
					sb.append(picpath);
					if (i != (addPicLayout.getChildCount() - 1)) {
						sb.append(",");
					}
				}
				ToolLoading.closeLoading(context);
				sendMsg(sb.toString());
			}
		});
	}

	// 上传单张图片
	private String uploadImgsyc(String path) {
		Bitmap bitmap = BitmapTools.createImageThumbnail(path);
		if (bitmap == null)
			return "";
		File f = new File(path);
		File newPath = new File(f.getParent(), f.getName() + "temp" + ".jpg");
		NativeUtil.compressBitmap(bitmap, 100, newPath.getAbsolutePath(), true);
		bitmap.recycle();
		String base64str = Base64.encodeToString(Utils.File2byte(newPath.getAbsolutePath()), Base64.NO_WRAP);
		Log2File.newInstant().log2File(base64str);
		Map<String, String> map = HttpUtil.getParams("app", "uploadpic", "act", "picupload", "type", type + "",
				"user_id", user_id + "", "portrait", base64str);
		String result = Http.getInstant().sendRequestSync(HttpConst.UPLOAD_PHOTO_URL, map);
		JSONObject jsonObject = JSON.parseObject(result);
		boolean isSucces = jsonObject.getBoolean("done");
		if (isSucces) {
			String photo = jsonObject.getString("retval");
			return photo;
		} else {
			Toast.makeText(Act_Quanzi_Fatie.this, "上传图片路径失败！", Toast.LENGTH_SHORT).show();
			return null;
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fatie_camera:
			Intent intent = new Intent(this, MultiImageSelectorActivity.class);
			// 是否显示拍摄图片
			intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
			// 最大可选择图片数量
			intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
			// 选择模式
			intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
			// // 默认选择
			// if(mSelectPath != null && mSelectPath.size()>0){
			// intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,
			// mSelectPath);
			// }
			startActivityForResult(intent, 1);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
				if (mSelectPath != null && mSelectPath.size() != 0) {
					mSelectPhoto = mSelectPath.get(0);
					pics.add(mSelectPhoto);
					handler.sendEmptyMessage(1);
				}
			}
		}
	}

	private void showSelectPic(ImageView view, String string) {
		ImageUtils.loadimgFromSDcard(view, string);
	}

	// 刷新LinearLayout
	private void refersh() {
		addPicLayout.removeAllViews();
		for (int i = 0; i < pics.size(); i++) {
			addPicLayout.addView(getView(i, pics.get(i)));
		}
		addPicLayout.addView(Img_Camera);
	}

	private View getView(int pos, String path) {
		itemView = LayoutInflater.from(this).inflate(R.layout.item_addpic, null);
		ImageView imView = (ImageView) itemView.findViewById(R.id.ItemAddPicImageView);
		ImageView delView = (ImageView) itemView.findViewById(R.id.ItemAddPicDelIcon);
		itemView.setTag(path);
		delView.setTag(path);
		delView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String p = (String) arg0.getTag();
				pics.remove(p);
				handler.sendEmptyMessage(1);
			}
		});
		showSelectPic(imView, path);
		return itemView;
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				refersh();
				break;
			case 2:
				String str = (String) msg.obj;
				Map<String, String> map = HttpUtil.getParams("app", "posttopic", "act", "add", "title", Str_Biaoti,
						"gid", id, "content", Str_content, "images", str);
				// 将图片地址上传给服务器
				Http.getInstant().sendRequest(Act_Quanzi_Fatie.this, true, HttpConst.BASEURL, map, new HttpListener() {
					@Override
					public void onHttpSuccess(String result) {
						Toast.makeText(Act_Quanzi_Fatie.this, "发布帖子成功", 1).show();
						finish();
						EventBus.getDefault().post("", "refresh");
					}

					@Override
					public void onHttpError(String error) {
					}
				});
				break;
			}
		};
	};
}
